package com.gl.portal.system.controller;

import com.alibaba.excel.EasyExcel;
import com.gl.common.constant.Constants;
import com.gl.common.util.SecurityUtils;
import com.gl.common.util.StringUtils;
import com.gl.framework.aspectj.annotation.Log;
import com.gl.framework.aspectj.enums.BusinessType;
import com.gl.framework.interceptor.annotation.RepeatSubmit;
import com.gl.framework.web.domain.PageData;
import com.gl.framework.web.response.Result;
import com.gl.portal.system.service.SysRoleService;
import com.gl.portal.system.service.SysUserService;
import com.gl.portal.system.vo.SysRoleVo;
import com.gl.portal.system.vo.SysUserVo;
import com.gl.portal.system.vo.export.UserExportVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户信息控制器
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController {

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;

    /**
     * 用户分页列表
     *
     * @param filter
     * @return
     */
    @GetMapping("/list")
    @PreAuthorize("@ps.hasPermi('system:user:list')")
    public PageData<SysUserVo> list(SysUserVo filter) {
        return userService.selectUserList(filter);
    }

    /**
     * 获取用户详细信息
     *
     * @param userId
     * @return
     */
    @GetMapping(value = {"/", "/{userId}"})
    @PreAuthorize("@ps.hasPermi('system:user:query')")
    public Map<String, Object> getInfo(@PathVariable(required = false) Long userId) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<SysRoleVo> roles = roleService.selectRoleAll();

        map.put("roles", SecurityUtils.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        if (StringUtils.isNotNull(userId)) {
            map.put("user", userService.selectUserById(userId));

            List<Long> list = roleService.selectRoleListByUserId(userId);
            map.put("roleIds", list == null ? new ArrayList<Long>() : list);
        }
        return map;
    }

    /**
     * 新增用户
     *
     * @param vo
     * @return
     */
    @RepeatSubmit
    @PostMapping
    @PreAuthorize("@ps.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    public Result add(@Validated @RequestBody SysUserVo vo) {
        String loginName = vo.getLoginName();
        if (Constants.NOT_UNIQUE.equals(userService.checkLoginNameUnique(loginName))) {
            return Result.fail(  "新增用户'" + loginName + "'失败，登录账号已存在");
        } else if (Constants.NOT_UNIQUE.equals(userService.checkPhoneUnique(vo))) {
            return Result.fail( "新增用户'" + loginName + "'失败，手机号码已存在");
        } else if (Constants.NOT_UNIQUE.equals(userService.checkEmailUnique(vo))) {
            return Result.fail(  "新增用户'" + loginName + "'失败，邮箱账号已存在");
        }
        vo.setPassword(SecurityUtils.encryptPassword(vo.getPassword()));
        userService.saveUser(vo);
        return Result.success();
    }

    /**
     * 修改用户
     *
     * @param vo
     * @return
     */
    @PutMapping
    @PreAuthorize("@ps.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    public Result edit(@Validated @RequestBody SysUserVo vo) {
        userService.checkUserAllowed(vo);

        if (Constants.NOT_UNIQUE.equals(userService.checkPhoneUnique(vo))) {
            return Result.fail(  "修改用户'" + vo.getLoginName() + "'失败，手机号码已存在");
        } else if (Constants.NOT_UNIQUE.equals(userService.checkEmailUnique(vo))) {
            return Result.fail(  "修改用户'" + vo.getLoginName() + "'失败，邮箱账号已存在");
        }

        userService.updateUser(vo);
        return Result.success();
    }

    /**
     * 删除用户
     *
     * @param userIds
     * @return
     */
    @DeleteMapping("/{userIds}")
    @PreAuthorize("@ps.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    public Result remove(@PathVariable List<Long> userIds) {
        userService.deleteUserByIds(userIds);
        return Result.success();
    }

    /**
     * 重置密码
     *
     * @param vo
     * @return
     */
    @PutMapping("/reset_pwd")
    @PreAuthorize("@ps.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.RESET_PASSWORD)
    public Result resetPwd(@RequestBody SysUserVo vo) {
        if (vo == null || StringUtils.isBlank(vo.getPassword())) {
            return Result.fail("password is empty");
        }
        userService.checkUserAllowed(vo);
        userService.resetPwd(vo);
        return Result.success();
    }

    /**
     * 状态修改
     *
     * @param vo
     * @return
     */
    @PutMapping("/status")
    @PreAuthorize("@ps.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    public Result changeStatus(@RequestBody SysUserVo vo) {
        userService.checkUserAllowed(vo);
        userService.updateUserStatus(vo);
        return Result.success();
    }

    /**
     * 导出
     *
     * @param filter
     * @param response
     * @throws IOException
     */
    @GetMapping("/export")
    @PreAuthorize("@ps.hasPermi('system:user:export')")
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    public void export(SysUserVo filter, HttpServletResponse response) throws IOException {
        // 查询数据
        PageData<SysUserVo> pageData = userService.selectUserList(filter);
        List<SysUserVo> data = pageData.getData();
        List<UserExportVo> exportData = data.stream().map(vo -> {
            UserExportVo exportVo = new UserExportVo();
            exportVo.setLoginName(vo.getLoginName());
            exportVo.setUserName(vo.getUserName());
            exportVo.setDeptName(vo.getDept().getDeptName());
            exportVo.setEmail(vo.getEmail());
            exportVo.setPhone(vo.getPhone());
            Integer gender = vo.getGender();
            exportVo.setGender(gender == 0 ? "男" : gender == 1 ? "女" : "未知");
            Integer status = vo.getStatus();
            exportVo.setStatus(status == 1 ? "正常" : "停用");
            exportVo.setCreator(vo.getCreator());
            exportVo.setCreateTime(vo.getCreateTime());
            return exportVo;
        }).collect(Collectors.toList());

        EasyExcel.write(response.getOutputStream(), UserExportVo.class).sheet("用户信息").doWrite(exportData);
    }
}
